﻿using DevExpress.XtraEditors;
using MesProjectWinform.Equipment.Output;
using MesProjectWinform.Equipment.Select;
using MesProjectWinform.Public;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MesProjectWinform.Equipment.Form.DeviceLedger
{
    /// <summary>
    /// 设备台账编辑
    /// </summary>
    public partial class DeviceLedgerEditForm : DevExpress.XtraEditors.XtraForm
    {
        public DeviceLedgerEditForm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 设备台账编号
        /// </summary>
        private long Id { get; set; }

        /// <summary>
        /// 回显数据
        /// </summary>
        public void GetDeviceLedgerData(DeviceLedgerOutput deviceLedgerOutput)
        {
            Id = deviceLedgerOutput.Id;
            DeviceLedgerName.Text = deviceLedgerOutput.DeviceLedgerName;
            DeviceSpeciFication.Text = deviceLedgerOutput.DeviceSpeciFication;
            DeviceBrand.Text = deviceLedgerOutput.DeviceBrand;
            DeviceType.Text = deviceLedgerOutput.DeviceType;
            DeviceNum.Text = deviceLedgerOutput.DeviceNum.ToString();
            DeviceBeginTime.Text = deviceLedgerOutput.DeviceBeginTime.ToString("yyyy-MM-dd");
            DeviceEnterTime.Text = deviceLedgerOutput.DeviceEnterTime.ToString("yyyy-MM-dd");
            Devicelocation.Text = deviceLedgerOutput.Devicelocation;
            DeviceHead.Text = deviceLedgerOutput.DeviceHead;
            DeviceRemark.Text = deviceLedgerOutput.DeviceRemark;
            DeviceTypeId.EditValue = deviceLedgerOutput.DeviceTypeId;
            WorkShopId.EditValue = deviceLedgerOutput.WorkShopId;
            SupplierId.EditValue = deviceLedgerOutput.SupplierId;
            DeviceuseDepartments.Text = deviceLedgerOutput.DeviceuseDepartments;
        }
        /// <summary>
        /// 获取车间和供应商数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DeviceLedgerEditForm_Load(object sender, EventArgs e)
        {
            #region 加载供应商数据
            List<SupplierOutput> supplierList = new List<SupplierOutput>()
                    {
                        new SupplierOutput()
                        {
                            Id = 1,
                            SupplierName = "供应商1"
                        },
                        new SupplierOutput()
                        {
                            Id = 2,
                            SupplierName = "供应商2"
                        },
                        new SupplierOutput()
                        {
                            Id = 3,
                            SupplierName = "供应商3"
                        }
                    };

            if (supplierList != null)
            {
                // 设置下拉列表的数据源
                SupplierId.Properties.DataSource = supplierList;

                // 设置显示和值字段
                SupplierId.Properties.DisplayMember = "SupplierName";
                SupplierId.Properties.ValueMember = "Id";

                // 设置下拉列表的列
                SupplierId.Properties.Columns.Clear();
                SupplierId.Properties.Columns.Add(new DevExpress.XtraEditors.Controls.LookUpColumnInfo("SupplierName", "供应商名称"));

                SupplierId.Properties.PopulateColumns();
                SupplierId.Properties.Columns[0].Visible = false;

                //// 设置下拉框显示样式
                DeviceTypeId.Properties.ShowHeader = false;
                DeviceTypeId.Properties.ShowFooter = false;
                DeviceTypeId.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
            }
            #endregion

            #region 加载车间数据
            List<WorkShopOutput> workShopOutputs = new List<WorkShopOutput>()
                    {
                        new WorkShopOutput()
                        {
                            Id = 1,
                            WorkShopName = "车间1"
                        },
                        new WorkShopOutput()
                        {
                            Id = 2,
                            WorkShopName = "车间2"
                        },
                        new WorkShopOutput()
                        {
                            Id = 3,
                            WorkShopName = "车间3"
                        },
                    };

            if (workShopOutputs != null)
            {
                // 添加数据源
                WorkShopId.Properties.DataSource = workShopOutputs;
                // 添加显示和值字段
                WorkShopId.Properties.DisplayMember = "WorkShopName";
                WorkShopId.Properties.ValueMember = "Id";
                // 设置下拉列表的列
                WorkShopId.Properties.Columns.Clear();
                WorkShopId.Properties.Columns.Add(new DevExpress.XtraEditors.Controls.LookUpColumnInfo("WorkShopName", "车间名称"));
                WorkShopId.Properties.PopulateColumns();
                WorkShopId.Properties.Columns[0].Visible = false;
                // 添加下拉框显示样式
                WorkShopId.Properties.ShowHeader = false;
                WorkShopId.Properties.ShowFooter = false;
                WorkShopId.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
            }
            #endregion
        }

        /// <summary>
        /// 获取设备类型下拉
        /// </summary>
        /// <returns></returns>
        public async Task GetSeelct()
        {
            using (var client = new HttpClient())
            {
                #region 加载设备类型数据
                var response = await client.GetStringAsync("http://47.110.243.157:5229/api/DeviceLedger/GetDeviceTypeValue");

                var result = JsonConvert.DeserializeObject<ApiResult<List<DeviceTypeOuput>>>(response);

                if (result != null && result.Data != null)
                {
                    // 设置下拉列表的数据源
                    DeviceTypeId.Properties.DataSource = result.Data;
                    // 设置显示和值字段
                    DeviceTypeId.Properties.DisplayMember = "DeviceTypeName";
                    DeviceTypeId.Properties.ValueMember = "Id";

                    // 设置下拉列表的列
                    DeviceTypeId.Properties.Columns.Clear();
                    DeviceTypeId.Properties.Columns.Add(new DevExpress.XtraEditors.Controls.LookUpColumnInfo("DeviceTypeName", "设备类型名称"));


                    // 设置下拉框显示样式
                    DeviceTypeId.Properties.ShowHeader = false;
                    DeviceTypeId.Properties.ShowFooter = false;
                    DeviceTypeId.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
                }
                #endregion
            }
        }

        /// <summary>
        /// 修改设备台账保存点击按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void UpdateDeviceLedgerButton1_Click(object sender, EventArgs e)
        {
            // 禁用保存按钮，防止重复提交
            simpleButton1.Enabled = false;

            try
            {
                // 1. 数据验证
                // 验证设备名称不能为空
                if (string.IsNullOrWhiteSpace(DeviceLedgerName.Text))
                {
                    XtraMessageBox.Show("设备名称不能为空", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    DeviceLedgerName.Focus();
                    return;
                }

                // 验证设备类型必须选择
                if (DeviceTypeId.EditValue == null)
                {
                    XtraMessageBox.Show("请选择设备类型", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    DeviceTypeId.Focus();
                    return;
                }

                // 验证设备数量为有效数字
                if (!int.TryParse(DeviceNum.Text, out int deviceNum))
                {
                    XtraMessageBox.Show("设备数量必须是有效数字", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    DeviceNum.Focus();
                    return;
                }

                // 2. 创建设备台账对象并赋值
                DeviceLedgerOutput deviceLedgerOutput = new DeviceLedgerOutput();
                deviceLedgerOutput.Id = Id; // 设置设备台账ID
                // 基本信息赋值
                deviceLedgerOutput.DeviceLedgerName = DeviceLedgerName.Text; // 设备名称
                deviceLedgerOutput.DeviceBrand = DeviceBrand.Text;           // 设备品牌
                deviceLedgerOutput.DeviceType = DeviceType.Text;             // 设备型号
                deviceLedgerOutput.DeviceSpeciFication = DeviceSpeciFication.Text; // 设备规格
                deviceLedgerOutput.DeviceNum = deviceNum;                    // 设备数量

                // 位置和责任信息赋值
                deviceLedgerOutput.Devicelocation = Devicelocation.Text;         // 位置
                deviceLedgerOutput.DeviceuseDepartments = DeviceuseDepartments.Text; // 使用部门
                deviceLedgerOutput.DeviceHead = DeviceHead.Text;                 // 负责人
                deviceLedgerOutput.DeviceRemark = DeviceRemark.Text;             // 备注

                // 处理生产日期字段，若未选择则默认为当前时间
                if (DeviceBeginTime.EditValue != null)
                {
                    deviceLedgerOutput.DeviceBeginTime = DeviceBeginTime.DateTime;
                }
                else
                {
                    deviceLedgerOutput.DeviceBeginTime = DateTime.Now;
                }

                // 处理入场时间字段，若未选择则默认为当前时间
                if (DeviceEnterTime.EditValue != null)
                {
                    deviceLedgerOutput.DeviceEnterTime = DeviceEnterTime.DateTime;
                }
                else
                {
                    deviceLedgerOutput.DeviceEnterTime = DateTime.Now;
                }

                // 3. 处理下拉框字段
                // 设备类型ID和名称
                if (DeviceTypeId.EditValue is DeviceTypeOuput deviceType)
                {
                    deviceLedgerOutput.DeviceTypeId = deviceType.Id;
                    deviceLedgerOutput.DeviceTypeName = deviceType.DeviceTypeName;
                }
                else if (DeviceTypeId.EditValue != null)
                {
                    try
                    {
                        deviceLedgerOutput.DeviceTypeId = Convert.ToInt64(DeviceTypeId.EditValue);
                    }
                    catch
                    {
                        XtraMessageBox.Show("设备类型数据格式无效", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        DeviceTypeId.Focus();
                        return;
                    }
                }


                // 供应商ID和名称
                if (SupplierId.EditValue is SupplierOutput supplier)
                {
                    deviceLedgerOutput.SupplierId = supplier.Id;
                    deviceLedgerOutput.SupplierName = supplier.SupplierName;
                }
                else if (SupplierId.EditValue != null)
                {
                    try
                    {
                        deviceLedgerOutput.SupplierId = Convert.ToInt64(SupplierId.EditValue);
                    }
                    catch
                    {
                        XtraMessageBox.Show("供应商数据格式无效", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        SupplierId.Focus();
                        return;
                    }
                }

                // 车间ID和名称
                if (WorkShopId.EditValue is WorkShopOutput workShop)
                {
                    deviceLedgerOutput.WorkShopId = workShop.Id;
                    deviceLedgerOutput.WorkShopName = workShop.WorkShopName;
                }
                else if (WorkShopId.EditValue != null)
                {
                    try
                    {
                        deviceLedgerOutput.WorkShopId = Convert.ToInt64(WorkShopId.EditValue);
                    }
                    catch
                    {
                        XtraMessageBox.Show("车间数据格式无效", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        WorkShopId.Focus();
                        return;
                    }
                }

                // 4. 添加审计字段（创建时间、更新时间）
                deviceLedgerOutput.UpdatedTime = DateTime.Now;

                // 5. 显示等待光标，准备调用API
                Cursor.Current = Cursors.WaitCursor;
                try
                {
                    // 创建HttpClient实例
                    using (var client = new HttpClient())
                    {
                        // 设置超时时间为30秒
                        client.Timeout = TimeSpan.FromSeconds(30);

                        // 将对象序列化为JSON字符串
                        var json = JsonConvert.SerializeObject(deviceLedgerOutput);
                        var content = new StringContent(json, Encoding.UTF8, "application/json");

                        // 发送POST请求到API
                        var response = await client.PutAsync("http://47.110.243.157:5229/api/DeviceLedger/UpdateDeviceLedger", content);

                        // 处理响应
                        if (response.IsSuccessStatusCode)
                        {
                            // 读取响应内容
                            var responseContent = await response.Content.ReadAsStringAsync();
                            // 反序列化为ApiResult<long>对象
                            var result = JsonConvert.DeserializeObject<ApiResult<long>>(responseContent);

                            // 判断返回结果
                            if (result != null && result.Code == ApiEnums.Success)
                            {
                                // 添加成功，提示并关闭窗口
                                XtraMessageBox.Show("设备台账修改成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                this.DialogResult = DialogResult.OK;
                                this.Close();
                            }
                            else
                            {
                                // 添加失败，显示错误信息
                                string errorMessage = result != null ? result.Message : "未知错误";
                                XtraMessageBox.Show($"修改失败: {errorMessage}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                        else
                        {
                            XtraMessageBox.Show($"请求失败，状态码: {response.StatusCode}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
                catch (HttpRequestException ex)
                {
                    XtraMessageBox.Show($"网络请求错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                catch (TaskCanceledException)
                {
                    XtraMessageBox.Show("请求超时，请检查网络连接或服务器状态", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                catch (JsonException ex)
                {
                    XtraMessageBox.Show($"JSON数据处理错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                catch (FormatException ex)
                {
                    XtraMessageBox.Show($"数据格式错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                catch (Exception ex)
                {
                    XtraMessageBox.Show($"保存时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            finally
            {
                // 恢复保存按钮状态
                simpleButton1.Enabled = true;
            }
        }
    }
}